//
//  httpserver.hpp
//  myhttpserver
//
//  Created by tgy on 2018/3/16.
//  Copyright © 2018年 tgy. All rights reserved.
//

#ifndef Httpserver_hpp
#define Httpserver_hpp

#include <stdio.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <fcntl.h>
#include <map>
#include "HttpServerRequest.hpp"
#include "HttpServerResponse.hpp"
#include "Client.hpp"
#define MAXEVENTLEN 1024

class Httpserver {

private:
    //服务器地址
    std::string basePath;
    std::string errorBasePath;
    std::string error404FilePath;
    std::string error500FilePath;
//    端口号
    int port;
//接收客户端的fd
    int sockfd;
    //服务器结构体
    struct sockaddr_in serverSockAddr;
    
    //kqueueid
    int kqueueId;
    
    struct kevent evlist[MAXEVENTLEN];
    //内否运行
    bool canRun;
    
    //客户端
    std::map<int, Client *> clients;
    
    void init();
    
    //更新ident状态
    void updateEvent(int ident,short filter,u_short flags,u_int fflags,int data,void *udata);
    //接收客户端连接
    void acceptAction();
    //读操作
    void readAction(struct kevent ev);
    //写操作
    bool writeAction(struct kevent ev);
    //断开连接
    void disconnectAction(struct kevent ev);
    //根据文件描述付获取client
    Client * getClientByFd(int fd);
    //操作
    void serverHander(char *content,Client *client);
    //分发
    void dispatchMethod();
    //get 处理
    void getHander(HttpServerRequest *request, HttpserverResponse *response);
    void postHander(HttpServerRequest *request,HttpserverResponse *response);
    //服务器错误处理
    void serverErrorHander(HttpServerRequest *request, HttpserverResponse *response);
public:
    Httpserver();
    ~Httpserver();
    bool start(int port = 8080);
    void run();
};

#endif /* httpserver_hpp */
